﻿using NHibernate;
using NLog;
using Susha.Models.Pages;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Susha.Models.Helpers
{
    public static class NewsRepository
    {
        private static Logger _logger = LogManager.GetCurrentClassLogger();

        public static void Save(News news)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    news.CreationDate = DateTime.Now;
                    session.Save(news);
                    transaction.Commit();
                }
            }
        }

        public static IList<News> GetSomeNews(PagesEnum page)
        {
            Int32 newsCount = 0;

            switch (page)
            {
                case PagesEnum.Home:
                    newsCount = CommonTools.NEWS_FOR_MAIN_COUNT;
                    break;
                case PagesEnum.News:
                    newsCount = CommonTools.NEWS_FOR_NEWS_COLUMN;
                    break;
            }

            using (ISession session = NHibernateHelper.OpenSession())
            {
                IList<News> result = session.QueryOver<News>().OrderBy(x => x.Id).Desc.Take(newsCount).List<News>();
                return result
                    ?? new List<News>();
            }
        }

        public static News GetNewsById(Int32 id)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                News news = session.QueryOver<News>().Where(x => x.Id == id).SingleOrDefault();
                //Рассмотреть вариант, когда новостей нет, когда новость "не угадали с id"
                if (news == null)
                {
                    news = new News();
                    _logger.Error("NewsRepository.GetNewsById({0}): Пусточе значение");
                }
                return news;
            }
        }
    }
}